package com.qqonline.conmon;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.nfc.Tag;
import android.util.Log;
import android.widget.Toast;

import com.qqonline.domain.Weather;
import com.qqonline.interfaces.GetWeather;
import com.qqonline.interfaces.IXmlParse;
import com.qqonline.mpf.CitySetting;
import com.qqonline.mpf.R;
import com.qqonline.service.db.WeatherService;

public class GetWeatherByCode implements GetWeather {

	private static final String TAG="GetWeatherByCode";
	private String code;
	private Activity active;
	private boolean isStop;
	private com.qqonline.conmon.async.AsyncGet get;
	public GetWeatherByCode(String code) {
		this.code=code;
		isStop=false;
	}
	@Override
	public void AsyncGet(Activity activity) {
		this.active=activity;
		final WeatherService service=new WeatherService(activity, DATA.DATAVERSION);
		get = new com.qqonline.conmon.async.AsyncGet(
				activity,
				new com.qqonline.conmon.async.AsyncGet.MyDoPostBack() {

					@Override
					public void DoPostBack(String json) {
						if (isStop) {
							return;
						}
						InputStream is=new ByteArrayInputStream(json.getBytes());
						IXmlParse parse=new PullWeatherParse();
						Weather weather=null;
						try {
							weather=parse.parse(is);
						} catch (Exception e) {
							e.printStackTrace();
						}
						if (weather == null) {
							return ;
						}
						service.setWeatherToDatebase(weather);
						try {
							String city=active.getResources().getStringArray(R.array.PreferenceArray)[0];
							SharedPreferences shared=active.getSharedPreferences(active.getResources().getStringArray(R.array.PreferenceFileNameArray)[0], 
									CitySetting.MODE_PRIVATE);
							SharedPreferenceUtil.setPreference(shared, city, service.GetEntity().get_city());
							((MPFApp) active.getApplication()).set_weatherInfoCache(service.GetEntity());	
							((MPFApp) active.getApplication()).set_cityNameCache(service.GetEntity().get_city());
							Intent intent=new Intent();
							intent.setAction(DATA.BroadcastPicClockActionName);
							active.sendBroadcast(intent);						
							Toast.makeText(active, R.string.weather_updata, Toast.LENGTH_SHORT).show();
						} catch (Exception e) {
							e.printStackTrace();
						}
						
					}
				}, false);
		get.execute(DATA.AutoWeatherByIP.replace("%s1", code));
	}
	@Override
	public void release() {
		get.release();
		active=null;
		Log.w(TAG,"release GetWeatherByCode");
	}

}
